package com.charles.video.gateway.service.impl;

import com.charles.video.common.core.constant.CacheConstants;
import com.charles.video.common.core.constant.GeneralConstants;
import com.charles.video.common.core.exception.CaptchaException;
import com.charles.video.common.core.responseDomain.AjaxResult;
import com.charles.video.common.core.utils.Base64;
import com.charles.video.common.core.utils.uuid.IdUtils;
import com.charles.video.common.redis.service.RedisService;
import com.charles.video.gateway.service.ValidateCodeService;
import com.google.code.kaptcha.Producer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.FastByteArrayOutputStream;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @author Charles-H
 * 
 * 验证码实现接口
 */
@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {

    @Resource(name = "captchaProducer")
    private Producer producer;

    @Autowired
    private RedisService redisService;

    /* 验证码生成 */
    @Override
    public AjaxResult createCaptcha() throws IOException, CaptchaException {
        AjaxResult success = AjaxResult.success();

        String uuid = IdUtils.simpleUUID();
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String capStr = null, code = null;
        BufferedImage image = null;

        capStr = code = producer.createText();
        image = producer.createImage(capStr);
        
        redisService.setCacheObject(verifyKey, code, GeneralConstants.CAPTCHA_EXPIRATION, TimeUnit.MINUTES);
        FastByteArrayOutputStream outputStream = new FastByteArrayOutputStream();

        try {
            ImageIO.write(image, "jpg", outputStream);
        } catch (IOException e) {
            return AjaxResult.error(e.getMessage());
        }

        success.put("uuid", uuid);
        success.put("img", Base64.encode(outputStream.toByteArray()));
        return success;
    }

    /* 验证码校验 */
    @Override
    public void checkCaptcha(String code, String uuid) {
        
        /* 验证码判空 */
        if (code.isEmpty()) {
            throw new CaptchaException("验证码不能为空");
        }

        /* 判断uuid是否为空 */
        if (uuid.isEmpty()) {
            throw new CaptchaException("验证码已失效");
        }

        /* 从redis中通过uuid获取到验证码内容 */
        String codeKey = CacheConstants.CAPTCHA_CODE_KEY + uuid;
        String captcha = redisService.getCacheObject(codeKey);

        /* 获取后删除redis中的这个验证码 */
        redisService.deleteObject(codeKey);

        /* 判断验证码是否正确 */
        if (!code.equalsIgnoreCase(captcha)) {
            throw new CaptchaException("验证码错误");
        }
    }
}
